package com.winit.schedule.job.tracker.event;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.winit.schedule.core.event.EventHandler;
import com.winit.schedule.core.model.AssignedTask;
import com.winit.schedule.core.repository.constants.LogType;
import com.winit.schedule.core.utils.NetUtils;
import com.winit.schedule.job.tracker.JobTrackerContext;
import com.winit.schedule.job.tracker.repository.ScheduleDataManager;

/**
 * 任务事件处理器
 * 
 * @author jianke.zhang 2015-3-31 下午2:02:34
 * @since 1.0
 */
public class TaskEventHandler implements EventHandler<TaskStatusChangeEvent> {

    private static Logger             logger = LoggerFactory.getLogger(TaskEventHandler.class);

    private final ScheduleDataManager scheduleDataManager;

    private final JobTrackerContext   jobTrackerContext;

    private String                    localIP;

    public TaskEventHandler(JobTrackerContext jobTrackerContext){
        this.jobTrackerContext = jobTrackerContext;
        this.scheduleDataManager = jobTrackerContext.getScheduleDataManager();
        localIP = NetUtils.getLocalIP();
    }

    @Override
    public void handle(TaskStatusChangeEvent event) {
        if (TaskEventType.TASK_COMPLETE.equals(event.getType())) {
            scheduleDataManager.logger(event.getTasks(), event.getTaskTrackerUuid(), LogType.COMPLETE_TASK);
        } else if (TaskEventType.TASK_PUSH.equals(event.getType())) {
            scheduleDataManager.logger(event.getTasks(), event.getTaskTrackerUuid(), LogType.PUSH_TASK);
        } else if (TaskEventType.TASK_STOP.equals(event.getType())) {
            scheduleDataManager.logger(event.getTasks(), event.getTaskTrackerUuid(), LogType.STOP_TASK);
        } else if (TaskEventType.TASK_RUNNER_FAILURE.equals(event.getType())) {
            /*try {
                scheduleDataManager.logger(event.getTasks(),
                    event.getException(),
                    event.getTaskTrackerUuid(),
                    LogType.TASK_RUNNER_FAILURE);
            } catch (Exception e) {
                logger.error("Log into write to database failed", e);
            }*/

            if (null != event.getTasks() && event.getTasks().size() > 0) {
                fireExecuteException(event.getTasks().get(0), event.getTaskTrackerUuid(), event.getException());
            }
        } else if (TaskEventType.TASK_EXE_FAILURE.equals(event.getType())) {
            /*try {
                scheduleDataManager.logger(event.getTasks(),
                    event.getException(),
                    event.getTaskTrackerUuid(),
                    LogType.TASK_EXE_FAILURE);
            } catch (Exception e) {
                logger.error("Log into write to database ", e);
            }*/

            if (null != event.getTasks() && event.getTasks().size() > 0) {
                fireExecuteException(event.getTasks().get(0), event.getTaskTrackerUuid(), event.getException());
            }
        }
    }

    public void fireExecuteException(AssignedTask task, String taskTrackerUuid, String exception) {
        try {

            String subject = "Task exception from uschedule[" + localIP + "]";
            StringBuilder content = new StringBuilder();
            content.append("TaskTracker UUID : " + taskTrackerUuid + "\n\r");
            content.append("TaskId : " + task.getTaskId() + "\n\r");
            content.append("TaskItem : " + task.getTaskItems() + "\n\r");
            content.append("Exception : " + "\n\r");
            content.append(exception);

            jobTrackerContext.getMailHelper().sendTextMail(task.getAlarmTo(), subject, content.toString());
        } catch (Throwable e){
            logger.error("send mail failure. ", e);
        }

    }
}
